package org.xgame.bizserver.cmdhandler.login;

import org.slf4j.Logger;
import org.xgame.bizserver.base.AsyncBizResult;
import org.xgame.bizserver.base.MyCmdHandlerContext;
import org.xgame.bizserver.cmdhandler.CmdHandlerLog;
import org.xgame.bizserver.module.login.LoginService;
import org.xgame.bizserver.msg.LoginServerProtocol;
import org.xgame.comm.cmdhandler.ICmdHandler;

/**
 * 用户登录指令处理器
 */
public class UserLoginCmdHandler implements
    ICmdHandler<MyCmdHandlerContext, LoginServerProtocol.UserLoginCmd> {
    /**
     * 日志对象
     */
    private static final Logger LOGGER = CmdHandlerLog.LOGGER;

    @Override
    public void handle(
        MyCmdHandlerContext ctx, LoginServerProtocol.UserLoginCmd cmdObj) {
        LOGGER.debug(
            "用户登录, propertyStr = {}",
            cmdObj.getPropertyStr()
        );

        AsyncBizResult<String> bizResult;
        bizResult = LoginService.getInstance().doLogin(
            cmdObj.getLoginMethod(),
            cmdObj.getPropertyStr()
        );

        if (null == bizResult) {
            return;
        }

        bizResult.returnValFunc((token) -> {
            if (null == token) {
                return;
            }

            LoginServerProtocol.UserLoginResult r;
            r = LoginServerProtocol.UserLoginResult.newBuilder()
                .setTicket(token)
                .build();

            ctx.writeAndFlush(r);
        });
    }
}
